import React, { useEffect, useState } from 'react'
import { Button, Swiper, SwiperItem, View, CoverView, CoverImage } from '@tarojs/components'
import { checkJoinEnterprise, getCacheUserType, checkLogin } from '@/utils/user'
import { USER_TYPE } from '@/utils/enum/common'
import { getFullSrc, getFullSrcs, getNavTop } from '@/utils/Helper'
import Taro from '@tarojs/taro'
import { getMenuListWithoutLogin } from '@/services/xiaoxi'
import styles from './index.module.scss'
import { getEnterpriseList } from '@/services/company'
import { identity } from 'lodash'

// nav 导航
export default function NavBarModal() {

  const [swiperFlag, setSwiperFlag] = useState(false);
  const [menuData, setMenuData] = useState(null);
  const [menuDataSize, setMenuDataSize] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [indicatorDots, setIndicatorDots] = useState(false);
  const [enterpriseList, setEnterpriseList] = useState([]);

  const swiperChange = (e) => {
    const current = e.detail.current
    if (menuData.length - current * 8 > 4) {
      setSwiperFlag(true)
    } else {
      setSwiperFlag(true)
    }
  }

  // 报事报修
  const report = (url, title, menu_id) => {
    Taro.navigateTo({ url: url })
  }

  const getEnterpriseListFn = async () => {
    if (checkLogin()) {
      const resp = await getEnterpriseList()
      setEnterpriseList(resp || [])
    }
  }

  const goWxArticle = (url) => {
    Taro.openOfficialAccountArticle({
      url: url, // 此处填写公众号文章连接
      success: res => {
      },
      fail: res => {
      }
    })
  }

  // 菜单循环
  const menus = (size) => {
    return menuData?.map((item, index) => {
      let menuName = item.name
      if (getCacheUserType() === USER_TYPE.STAFF && menuName === '员工管理') {
        menuName = '企业通讯录'
      }
      if (index >= size * 8 && index < (size + 1) * 8) {
        return (
          <CoverView
            className={styles.Exhibition}
            onClick={() => {
              if (item.menu_type === 2) {
                goWxArticle(item?.router)
              } else {
                if (item?.menu_id === 'crbdo4upq9nionlcdvdg' || 'c9l2ffag1hf8r4va2kg2') {
                  report(item?.router, item.name, item.menu_id)
                } else {
                  if (!checkLogin()) {
                    // 用户未登录
                    setShowLoginModal(true)
                  } else {
                    const isJoin = enterpriseList.length > 0
                    if (isJoin) {
                      report(item?.router, item.name, item.menu_id)
                    } else {
                      setShowModal(!isJoin)
                    }
                  }
                }
              }
            }}
          >
            <CoverImage className={styles.photo} src={getFullSrc(item?.icon)}></CoverImage>
            <CoverView className={styles.words}>{menuName}</CoverView>
          </CoverView>
        )
      }
    })
  }


  const goSearchCompany = () => {
    setShowModal(false)
    Taro.navigateTo({ url: '/pages/search-company/index' })
  }


// 获取菜单列表
const menuList = () => {
  getMenuListWithoutLogin().then((res) => {
    if (res?.data) {
      // 替换菜单数据中的路径
      const updatedMenuData = res?.data.map(item => {
        // 如果菜单项的 `icon` 字段中包含目标路径，进行替换
        if (item.icon && item.icon.includes('/s/park/caa2a60e-76d2-4396-853e-dcc5e7663052/编组 17@2x.png')) {
          item.icon = getFullSrcs('documents/bsbx.jpg');  
        }
        if (item.icon && item.icon.includes('/s/park/651021ab-6b8c-4fc9-a083-a8840b113b3b/编组 22 (1).png')) {
          item.icon = getFullSrcs('documents/fkdj.jpg');  
        }
        if (item.icon && item.icon.includes('/s/park/b7c292df-8635-4f94-b20d-f243825c1433/wodepaiban_2.png')) {
          item.icon = getFullSrcs('documents/fkgl.jpg');
        }
        if (item.icon && item.icon.includes('/s/park/386899b9-453e-455b-afcb-90d4e2b1d9d4/yingjichuzhi_2.png')) {
          item.icon = getFullSrcs('documents/jfcx.jpg');
        }
        if (item.icon && item.icon.includes('/s/park/5c671da7-e646-41c5-a8e1-1818915cce4e/企业人员.png')) {
          item.icon = getFullSrcs('documents/yggl.jpg');
        }
        return item; // 返回修改后的菜单项
      });

      // 将更新后的菜单数据推送新的菜单项
      updatedMenuData.push(
        {
          hidden: 0,
          icon: getFullSrcs('documents/syxssc.png'),
          is_completed: 2,
          menu_id: "c9l2ffag1hf8r4va2kg5",
          name: "线上商城",
          parent_id: "c9l27nag1hf8r4va2k80",
          parent_path: "c9f6n42g1hfbekqmc6ag/c9l27nag1hf8r4va2k80",
          router: "/pages/shop/index",
          sequence: 8000000,
          title: "线上商城",
          visible: 2,
        }
      );

      const arr = [];
      const num = updatedMenuData.length / 8;
      for (let i = 0; i < num; i += 1) {
        arr.push(i);
      }
      
      if (arr.length > 1) {
        setIndicatorDots(true);
      }

      if (updatedMenuData.length <= 4) {
        setSwiperFlag(false);
      } else {
        setSwiperFlag(true);
      }

      // 更新菜单数据和大小
      setMenuData(updatedMenuData);
      setMenuDataSize(arr);
    }
  });
}


  useEffect(() => {
    menuList()
    getEnterpriseListFn()
  }, [])


  return (
    <View>
      <CoverView className={styles.navBarModal} style={{ top: `${getNavTop()}px` }}>
        {/*轮播*/}
        <CoverView className={styles.banner}>
          <CoverView className={styles.bord}>
            <Swiper
              className={swiperFlag ? `${styles.swiper}` : `${styles.noSwiper}`}
              indicatorColor='#E7E5E8'
              indicatorActiveColor='#1B69FD'
              indicatorDots={indicatorDots}
              onChange={(e) => swiperChange(e)}
            >
              {menuDataSize?.map((size) => {
                return (
                  <SwiperItem className={styles.swiperImgContent} key={size}>
                    <CoverView className={styles.choice}>{menus(size)}</CoverView>
                  </SwiperItem>
                )
              })}
            </Swiper>
          </CoverView>
        </CoverView>
      </CoverView>
      {showLoginModal ? <CoverView className={styles.modal}>
        <CoverView className={styles.modalCon}>
          <CoverView className={styles.modalHeader}>提示</CoverView>
          <CoverView className={styles.modalContent}>请在登录后使用此功能</CoverView>
          <CoverView className={styles.modalButton}>
            <Button onClick={() => {
              setShowLoginModal(false)
              Taro.navigateTo({ url: '/pages/login/index' })
            }}>确定</Button>
          </CoverView>
        </CoverView>
      </CoverView> : null}

      {showModal ? <CoverView className={styles.modal}>
        <CoverView className={styles.modalCon}>
          <CoverView className={styles.modalHeader}>提示</CoverView>
          <CoverView className={styles.modalContent}>您还没有加入企业，请咨询企业管理员加入企业</CoverView>
          <CoverView className={styles.modalButton}>
            <Button onClick={() => {
              setShowModal(false)
              Taro.navigateTo({ url: '/pages/search-company/index' })
            }}>确定</Button>
          </CoverView>
        </CoverView>

      </CoverView> : null}
    </View>


  )
}
